package cn.pconline.autoclub.web;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.PromotionPublish;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.PromotionService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zhouruxuan
 * @date 2014年10月17日 上午8:56:27
 */
@Controller
public class PromotionController {

    @Autowired
    private PromotionService promotionService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private MemberService memberService;
    @Autowired
    private IntfService intfService;
    @Autowired
    private ClubService clubService;
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(PromotionController.class);
    private static final int TOP_NUM_LOCAL_CLUB = 3;
    private static final int TOP_NUM_LOCAL_PROMOTION = 5;

    /**
     * 返回相关Json信息
     *
     * @param resp
     * @param str
     * @param callback
     */
    private void printMsg(HttpServletResponse resp, String str, String callback) {
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("response输出出错了", ex);
        }
    }

    /**
     * 获取同城车友会（前几名）、同城优惠（前几条）
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/club/listLocalClubAndPromotions.do", method = RequestMethod.GET)
    public void listLocalClubAndPromotions(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long provinceId = WebUtils.paramLong(request, "provinceId", 0L);
        long cityId = WebUtils.paramLong(request, "cityId", 0L);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", 2);
        JSONArray jsonArrayClub = new JSONArray();
        JSONArray jsonArrayPromotion = new JSONArray();
        JSONObject json = new JSONObject();
        //provinceId为必传参数
        if (provinceId == 0L) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "非法参数provinceId！");
            printMsg(response, json.toString(), callback);
            return;
        }
        //获取同城车友会前3名的信息
        List<Club> clubs = clubService.listClubByCityId(cityId, provinceId, TOP_NUM_LOCAL_CLUB);
        for (Club club : clubs) {
        	JSONObject jsonObject = clubService.setTopClub2Json(club, sourceAgent);
            jsonArrayClub.add(jsonObject);
        }
        //获取同城优惠前5条的记录
        List<PromotionPublish> promotionPublishs = promotionService.listPromotionPublishByCondition(provinceId, cityId, TOP_NUM_LOCAL_PROMOTION);
        for (PromotionPublish promotionPublish : promotionPublishs) {
        	JSONObject jsonObject = promotionService.setPromotionPublishToJson(promotionPublish, sourceAgent);
            jsonArrayPromotion.add(jsonObject);
        }
        json.put("sameCityClubCount", clubs == null ? 0 : clubs.size());
        json.put("sameCityPreferentialCount", promotionPublishs == null ? 0 : promotionPublishs.size());
        json.put("sameCityClubData", jsonArrayClub);
        json.put("preferentialData", jsonArrayPromotion);
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取同城车友会、同城优惠列表！");
        printMsg(response, json.toString(), callback);
    }

    /**
     * 同城优惠活动列表显示(APP接口）
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/club/listLocalPromotion.do", method = RequestMethod.GET)
    public void listLocalPromotion(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long provinceId = WebUtils.paramLong(request, "provinceId", 0L);
        long cityId = WebUtils.paramLong(request, "cityId", 0L);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", 2);
        int pageSize = WebUtils.paramInt(request, "pageSize", 20);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();

        //provinceId为必传参数
        if (provinceId == 0L) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "非法参数provinceId！");
            printMsg(response, json.toString(), callback);
            return;
        }

        //根据ProviceId、CidtyID获取同城优惠活动
        Pager<PromotionPublish> pager = promotionService.pagePromotionPublish(provinceId, cityId, pageNo, pageSize);
        WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());
        if (pager != null) {
            for (PromotionPublish promotionPublish : pager.getResultList()) {
                JSONObject jsonObject = promotionService.setPromotionPublishToJson(promotionPublish, sourceAgent);
                jsonArray.add(jsonObject);
            }
        }

        json.put("data", jsonArray);
        json.put("total", pager.getTotal());
        json.put("pageNo", pager.getPageNo());
        json.put("pageSize", pager.getPageSize());
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取同城优惠活动列表！");
        printMsg(response, json.toString(), callback);
    }
}
